import curses

class MenuWin:

    def __init__(self, screen, items: list=list(), index: int=0):
        max_y, _ = screen.getmaxyx()

        self.win = curses.newwin(max_y-3, 20, 3, 0)
        self.screen = screen
        self.is_current = False
        
        self.title = "Menu"

        self.index = index
        self.items = items

    def _is_valid_operand(self, other):
        return (hasattr(other, "title") and
                hasattr(other, "items"))

    def __eq__(self, other):
        if not self._is_valid_operand(other): return False
        return self.title == other.title 

    def clear(self):
        self.win.erase()

    def draw(self):
        max_y, max_x = self.screen.getmaxyx()

        if self.is_current: self.win.attron(curses.A_BOLD)

        self.win.box()
        self.win.addstr(0, 2, self.title)
        
        self.win.attroff(curses.A_BOLD)

        y = 1
        index = 0
        for item in self.items:
            self.win.addstr(y, 1, item.title)
            y += 1
            index += 1

    def move_up(self):
        self.index -= 1
        if self.index < 0:
            self.index = len(self.items) - 1

    def move_down(self):
        self.index += 1
        if self.index >= len(self.items):
            self.index = 0

    def refresh(self):
        self.win.refresh()

    def getch(self):
        return self.win.getch()

    def set_current(self):
        self.is_current = True

    def set_uncurrent(self):
        self.is_current = False

    def get_current_item(self):
        if len(self.items) == 0: return -1, None
        return self.index, self.items[self.index]

    def update(self, items: list=list()):
        self.items = items
        self.index = 0

